<template>
  <div class="container">

    <sq-header :selected="1"></sq-header>

    <div class="order">
      <div class="order-tips">订单信息</div>
      <sq-course-item :item="courseDetail" :key="courseDetail.id" @clickCourse="goToCourseDetail(courseDetail)"></sq-course-item>
    </div>

    <form id="pay-order-form" method="post" action="/page/order/create" target="_blank">
      <input name="orderSN" type="hidden" v-model="orderSN">
      <input name="payType" type="hidden" v-model="payType">
      <input name="courseId" type="hidden" v-model="courseId">
      <input name="channel" type="hidden" v-model="channel">
      <div class="order-tips">请选择支付方式</div>
      <div class="pay-choose">
          <div class="pay-choose-item" v-if="!isInWeChat">
            <div class="pay-info">
              <img src="../assets/zhifubao.png">
              <label>支付宝支付</label>
            </div>
            <input type="radio" id="pay-zhifubao" value="0" v-model="payType">
            <label for="pay-zhifubao"></label>
          </div>
          <div class="pay-choose-item">
            <div class="pay-info">
              <img src="../assets/weixin.png">
              <label>微信支付</label>
            </div>
            <input type="radio" id="pay-weixin" value="1" v-model="payType">
            <label for="pay-weixin"></label>
          </div>
      </div>
    </form>

    <div class="sq-footer">
      <button class="sq-footer-buy" @click="makeOrderAndPay" style="outline: none">立即支付（¥{{courseDetail.discPrice|priceFormat}}）</button>
    </div>

  </div>
</template>

<script>
import Vue from 'vue';
import { mapGetters } from 'vuex';
import Cookies from 'js-cookie';
import { Toast } from 'mint-ui';
import SqHeader from '../components/Header'
import SqCourseItem from '../components/CourseItem'
Vue.component(SqHeader.name, SqHeader)
Vue.component(SqCourseItem.name, SqCourseItem)
import {getCourseDetail, getOrderSN, getOrderStatus, createWxOrder} from '../api/index'

var ua = navigator.userAgent.toLocaleLowerCase();

export default {
  name: 'Buy',
  data () {
    return {
      courseId:"",
      orderSN:"",
      payType: "0",
      refreshCount: 0,
      courseDetail: {},
      stopRefresh: false,
      isInWeChat: /(micromessenger)/.test(ua),
    }
  },
  created () {
      this.courseId = this.$route.params.id;
      //this.randId = this.$route.params.randId;
      var reg = /randId=([^&]*)/
      if(reg.test(location.href)) {
          this.randId = RegExp.$1;
      }
      if(this.isInWeChat) {
        this.payType = "1";
      }
      var that = this;
      getCourseDetail(this.courseId, this.randId).then(function(resp){
        that.courseDetail = resp.data;
        if(that.courseDetail.hasBuy){
          that.$router.replace({ name: 'Course', params: { id: that.courseId, randId: that.randId }});
        }
      }).catch(function(err){
        console.log(err);
        that.$router.replace('/error/404');
      });
      if (!this.orderSN) {
        getOrderSN(this.$route.params.id).then(function(resp){
          that.orderSN = resp.data;
        }).catch(function(err){
          console.log(err);
          that.$router.replace('/error/500');
        });
      }
  },
  computed: {
    ...mapGetters([
      'channel'
    ])
  },
  mounted () {
    this.$store.dispatch("toggleBuyBarItem", {
      showBuyBar: true
    });
  },
  destroyed() {
    this.$store.dispatch("toggleBuyBarItem", {
      showBuyBar: false
    });
    this.stopRefresh = true;
  },
  methods: {
    goToCourseDetail(item) {
      this.$router.push({ name: 'Course', params: { id: item.id, randId: item.randId }})
    },
    refreshOrderStatus() {
      this.refreshCount += 1;
      var that = this;
      getOrderStatus(this.orderSN).then(function(resp){
        var status = resp.data;
        /*
         * 0 待支付
         * 1 已支付
         * 2 支付失败
         * 3 用户取消
         * 4 系统超时
         */
         if(status === 1){
            window._hmt.push(['_trackEvent', '订单', '支付成功', '课程号：' + that.courseId]);
           const islogin = that.$store.getters.islogin;
           if(islogin) {
             that.$router.replace({ name: 'Course', params: { id: that.courseId, randId: that.randId }});
           } else {
             that.$router.replace({name: 'Bind', params: {orderSN: that.orderSN}});
           }
            return;
         }else if(status === 3){
            Toast({
              message: '已取消支付',
              duration: 3000
            });
            return;
         }
         // 限制刷的次数（1个小时订单就超时了）, 后面刷新频率越来越低
         if(that.refreshCount < 100 && !that.stopRefresh){
            setTimeout(that.refreshOrderStatus, that.refreshCount * 100 + 3000);
         }
      }).catch(function(err){
        console.log(err);
      });
    },
    wxJSPay(data) {
      var that = this;
      /* eslint-disable */
      WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
              "appId": data.appId,     //公众号名称，由商户传入
              "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数
              "nonceStr": data.nonceStr, //随机串
              "package": data.package,
              "signType": data.signType,         //微信签名方式：
              "paySign": data.paySign //微信签名
          },
          function(res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
              const islogin = that.$store.getters.islogin;
              window._hmt.push(['_trackEvent', '订单', '支付成功', '课程号：' + that.courseId]);
              if(islogin) {
                that.$router.replace({ name: 'Course', params: { id: that.courseId, randId: that.randId }});
              } else {
                that.$router.replace({name: 'Bind', params: {orderSN: that.orderSN}});
              }
              return;
            } else {
              // 由产品决定是否提示，这里基本上是用户取消支付了
            }
          }
      );
    },
    makeOrderAndPay(){
      if(this.isInWeChat && parseInt(this.payType) === 0) {
        Toast({
          message: '请选择在浏览器里打开购买页面',
          duration: 3000
        });
        return;
      }
      if(!this.orderSN) {
        return;
      }
      //if(/\?accessTime=(\d*)/.test(window.location.href)) {
      //  Cookies.set('accessTime', RegExp.$1, { expires: 7 });
      //  Cookies.set('orderSN', this.orderSN, { expires: 7 });
      //}
      // 增加事件统计
      window._hmt.push(['_trackEvent', '订单', '开始支付', '课程号：' + this.courseId]);
      // 10秒钟以后 当前页面开始刷新支付状态
      this.refreshCount = 0;
      setTimeout(this.refreshOrderStatus, 10000);
      // 提交下单请求
      var buyForm = window.document.getElementById("pay-order-form");
      if(!this.isInWeChat){
        buyForm.submit();
      } else {
        var openId = Cookies.get('wx_open_id');
        var that = this;
        createWxOrder(openId, this.courseId, this.orderSN, this.channel).then(function(resp){
          var data = resp.data;
          that.wxJSPay(data);
        }).catch(function(err){
          Toast({
            message: '下单失败：' + err,
            duration: 3000
          });
        });
      }
    }
  }
}
</script>

<style scoped>

  .container {
  	width: 100%;
  	height: 100%;
  	margin: 0px;
  	padding: 0px;
  }

  .order-tips {
    height: 40px;
    background-color: #F7F7F7;
    text-align: left;
    display: flex;
    align-items: flex-end;
    padding-left: 12px;
    padding-bottom: 8px;
    font-size: 16px;
    color: #999999;
  }
  .pay-choose-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 44px;
    padding: 0 10px;
    line-height: 44px;
    border-bottom: 1px solid #ccc;
  }

  input[type=radio] {
    display:none;
  }

  input[type=radio] + label
  {
    background: url("../assets/checkbox_unselect.png") 0 0px no-repeat;
    height: 18px;
    width: 18px;
    padding: 0 0 0 0px;
    background-size: cover;
  }

  input[type=radio]:checked + label
  {
    background: url("../assets/checkbox_selected.png") 0 0px no-repeat;
    height: 18px;
    width: 18px;
    padding: 0 0 0 0px;
    background-size: cover;
  }

  .pay-info {
    display: flex;
    align-items: center;
  }

  .pay-info img {
    height: 27px;
    width: 27px;
    margin-right: 14px;
  }

  .sq-footer {
    position: fixed;
    left: 0px;
    bottom: 0px;
    height: 44px;
    width: 100%;
    border-top: 1px solid #cccccc;
  }

  .sq-footer button {
    height: 100%;
    border: 0px;
    font-size: 16px;
  }

  .sq-footer-buy {
    flex-grow: 2;
    background-color: #fe6b40;
    color: #ffffff;
    font-size: 16px;
    width: 100%;
  }

</style>
